import { registerAs } from '@nestjs/config';
import { TypeOrmModuleOptions } from '@nestjs/typeorm';

export default registerAs('typeorm', (): TypeOrmModuleOptions => {
  // 验证必要环境变量
  if (!process.env.DB_NAME) {
    throw new Error('DB_NAME environment variable is required');
  }

  return {
    type: 'mysql',
    host: process.env.DB_HOST || 'localhost',
    port: parseInt(process.env.DB_PORT || '3306', 10),
    username: process.env.DB_USERNAME || 'root',
    password: process.env.DB_PASSWORD || '',
    database: process.env.DB_NAME, // 必须存在
    entities: [__dirname + '/../**/*.entity{.ts,.js}'],
    synchronize: process.env.NODE_ENV !== 'production',
    logging: process.env.NODE_ENV === 'development',
    extra: {
      charset: 'utf8mb4_unicode_ci', // 支持 emoji
    },
    // 生产环境推荐配置
    ...(process.env.NODE_ENV === 'production' && {
      ssl: {
        rejectUnauthorized: true,
      },
      poolSize: 10,
    })
  };
});